import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    userInfo: (() => {
      const stored = localStorage.getItem('userInfo')
      return stored && stored !== 'undefined' ? JSON.parse(stored) : null
    })(),
    // 访问token
    accessToken: (() => {
      const stored = localStorage.getItem('accessToken')
      return stored && stored !== 'undefined' ? stored : null
    })(),
    // 刷新token
    refreshToken: (() => {
      const stored = localStorage.getItem('refreshToken')
      return stored && stored !== 'undefined' ? stored : null
    })(),
    // 用户权限
    permissions: (() => {
      const stored = localStorage.getItem('permissions')
      return stored && stored !== 'undefined' ? JSON.parse(stored) : []
    })()
  },
  
  mutations: {
    /**
     * 设置用户信息
     */
    setUserInfo(state, userInfo) {
      if (userInfo && Object.keys(userInfo).length > 0) {
        state.userInfo = userInfo
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        console.log('setUserInfo - 保存用户信息:', userInfo)
      } else {
        console.warn('setUserInfo - 无效的用户信息:', userInfo)
      }
    },
    
    /**
     * 设置访问token
     */
    setToken(state, token) {
      if (token && token !== 'undefined') {
        state.accessToken = token
        localStorage.setItem('accessToken', token)
        console.log('setToken - 保存token:', token)
      } else {
        console.warn('setToken - 无效的token:', token)
      }
    },
    
    /**
     * 设置刷新token
     */
    setRefreshToken(state, token) {
      state.refreshToken = token
      localStorage.setItem('refreshToken', token)
    },
    
    /**
     * 设置用户权限
     */
    setPermissions(state, permissions) {
      if (permissions && Array.isArray(permissions) && permissions.length > 0) {
        state.permissions = permissions
        localStorage.setItem('permissions', JSON.stringify(permissions))
        console.log('setPermissions - 保存权限:', permissions)
      } else {
        console.warn('setPermissions - 无效的权限:', permissions)
      }
    },
    
    /**
     * 清除用户信息
     */
    clearUserInfo(state) {
      state.userInfo = null
    },
    
    /**
     * 清除token
     */
    clearToken(state) {
      state.accessToken = null
      state.refreshToken = null
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
    },
    
    /**
     * 清除所有认证信息
     */
    clearAuth(state) {
      state.userInfo = null
      state.accessToken = null
      state.refreshToken = null
      state.permissions = []
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
    }
  },
  
  actions: {
    /**
     * 登录
     */
    async login({ commit }, loginData) {
      try {
        const { login } = await import('@/api/request')
        const response = await login(loginData)
        
        // 现在response直接是data字段的内容
        if (response && response.accessToken) {
          const { accessToken, refreshToken, ...userInfo } = response
          
          // 保存token和用户信息
          commit('setToken', accessToken)
          commit('setRefreshToken', refreshToken)
          commit('setUserInfo', userInfo)
          
          // 解析权限
          if (userInfo.authorities) {
            const permissions = userInfo.authorities.split(',').filter(p => p.trim())
            commit('setPermissions', permissions)
          }
          
          return response
        } else {
          throw new Error('登录响应数据无效')
        }
      } catch (error) {
        throw error
      }
    },
    
    /**
     * 登出
     */
    async logout({ commit }) {
      try {
        const { logout } = await import('@/api/request')
        await logout()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 无论是否成功，都清除本地数据
        commit('clearAuth')
      }
    },
    
    /**
     * 刷新token
     */
    async refreshToken({ commit, state }) {
      try {
        const { refreshToken } = await import('@/api/request')
        const response = await refreshToken({
          refreshToken: state.refreshToken
        })
        
        if (response.code === 0) {
          const { accessToken, refreshToken: newRefreshToken } = response.data
          
          // 更新token
          commit('setToken', accessToken)
          commit('setRefreshToken', newRefreshToken)
          
          return response
        } else {
          throw new Error(response.msg || '刷新token失败')
        }
      } catch (error) {
        // 刷新失败，清除认证信息
        commit('clearAuth')
        throw error
      }
    },
    
    /**
     * 获取当前用户信息
     */
    async getCurrentUser({ commit }) {
      try {
        const { getCurrentUser } = await import('@/api/request')
        const response = await getCurrentUser()
        
        // 现在response直接是data字段的内容
        if (response) {
          commit('setUserInfo', response)
          return response
        } else {
          throw new Error('获取用户信息失败')
        }
      } catch (error) {
        throw error
      }
    }
  },
  
  getters: {
    /**
     * 是否已登录
     */
    isLoggedIn: state => {
      const stateToken = state.accessToken
      const localToken = localStorage.getItem('accessToken')
      const hasToken = !!(stateToken && stateToken !== 'undefined') || !!(localToken && localToken !== 'undefined')
      const hasUserInfo = !!(state.userInfo && Object.keys(state.userInfo).length > 0)
      
      console.log('isLoggedIn检查 - state.accessToken:', stateToken)
      console.log('isLoggedIn检查 - localStorage.accessToken:', localToken)
      console.log('isLoggedIn检查 - state.userInfo:', state.userInfo)
      console.log('isLoggedIn检查 - hasToken:', hasToken, 'hasUserInfo:', hasUserInfo)
      
      return hasToken && hasUserInfo
    },
    
    /**
     * 获取用户信息
     */
    userInfo: state => state.userInfo,
    
    /**
     * 获取用户权限
     */
    permissions: state => state.permissions,
    
    /**
     * 检查是否有指定权限
     */
    hasPermission: state => permission => {
      return state.permissions.includes(permission)
    },
    
    /**
     * 检查是否有任意一个权限
     */
    hasAnyPermission: state => permissions => {
      if (!Array.isArray(permissions)) {
        permissions = [permissions]
      }
      return permissions.some(permission => state.permissions.includes(permission))
    }
  }
}) 